package com.wangcang.widgetlibrary.pageindicator;

import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wangcang.widgetlibrary.R;
import com.wangcang.widgetlibrary.tools.ConvertUtils;
import com.wangcang.widgetlibrary.tools.LogUtils;
import com.wangcang.widgetlibrary.viewindicator.CustomViewPagerInternal;


/**
 * Created by jack.dong on 2017/1/14.
 */

public class SlideBarView extends RelativeLayout {
    private CustomViewPagerInternal mViewPagerInternal;

    public void setViewPagerInternal(CustomViewPagerInternal mViewPagerInternal) {
        this.mViewPagerInternal = mViewPagerInternal;
        setTotalPage(mViewPagerInternal.getAdapter().getCount());
        mViewPagerInternal.setOnPageChangeListener(new CustomViewPagerInternal.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setCurrPage(position);
                slideBlock.setText("" + (currPage+1));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    public SlideBarView(Context context) {
        super(context);
        init(context);
    }

    public SlideBarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public SlideBarView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    Context mContext = null;
    LayoutInflater mInflater = null;
    View v = null;
    View slideBar = null;
    PopupWindow popupWindow = null; // 点击后弹出的pop
    TextView popTextV = null; // 点击后弹出的pop上的text
    TextView slideBlock = null; // 滑块
    int dp40 = 0;
    String bound = "no"; // no表示没到边界，left为到左边界了，right表示到右边界了
    int currPage = 0; // 当前选中了哪一页
    private void init(Context context) {
        mContext = context;
        mInflater = LayoutInflater.from(mContext);
        dp40 = ConvertUtils.dip2px(mContext, 40);
        v = mInflater.inflate(R.layout.slide_bar_layout, null);
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        addView(v, params);

        slideBar = v.findViewById(R.id.slide_bar_view);
        slideBlock = (TextView) v.findViewById(R.id.slide_block);
        slideBar.setOnTouchListener(new OnTouchListener() {
            int currX = 0;
            int startX = 0;
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (MotionEvent.ACTION_DOWN == event.getAction()) {
                    currX = (int) event.getX();
                    startX = (int) event.getX();

                    // 设置滑块的滑动, 手指第一次点下去把滑块放到手指上
                    int left = currX - slideBlock.getMeasuredWidth() / 2;
                    int top = slideBlock.getTop();
                    int right = left + slideBlock.getMeasuredWidth();
                    int bottom = slideBlock.getBottom();
                    if (left < 0) {
                        left = 0;
                        right = slideBlock.getWidth();
                    }
                    if (right > slideBar.getMeasuredWidth()) {
                        left = slideBar.getMeasuredWidth() - slideBlock.getMeasuredWidth();
                        right = slideBar.getMeasuredWidth();
                    }
                    slideBlock.layout(left, top, right, bottom);

                    // 手指按下弹出popwindow
                    int[] loc = new int[2];
                    slideBar.getLocationInWindow(loc);
//                    popupWindow.showAsDropDown(slideBar, 0, 0);
                    popupWindow.showAtLocation(slideBar, Gravity.NO_GRAVITY, loc[0], loc[1]-popupWindow.getHeight());
                    popupWindow.update(currX, loc[1] - dp40, popupWindow.getWidth(), popupWindow.getHeight(), true);
                    currPage = currX * totalPage / slideBar.getMeasuredWidth();
                    if (currPage < 0) {
                        currPage = 0;
                    }
                    if (currPage >= totalPage) {
                        currPage = totalPage - 1;
                    }
                    popTextV.setText((currPage + 1) + "");
                    slideBlock.setText("" + (currPage+1));
                }
                else if (MotionEvent.ACTION_MOVE == event.getAction()) {
                    currX = (int) event.getX();
                    currPage = currX * totalPage / slideBar.getMeasuredWidth();
                    if (currPage < 0) {
                        currPage = 0;
                    }
                    if (currPage >= totalPage) {
                        currPage = totalPage - 1;
                    }
                    // 设置滑块的滑动
                    int left = currX - slideBlock.getMeasuredWidth() / 2;
                    int top = slideBlock.getTop();
                    int right = left + slideBlock.getMeasuredWidth();
                    int bottom = slideBlock.getBottom();

                    // 左边界处理
                    if (left <= 0) {
                        bound = "left";
                    }
                    else  if (right >= slideBar.getMeasuredWidth()) {
                        bound = "right";
                    }
                    else {
                        bound = "no";
                    }

                    if (left < 0) {
                        left = 0;
                        right = slideBlock.getWidth();
                    }

                    if (right > slideBar.getMeasuredWidth()) {
                        left = slideBar.getMeasuredWidth() - slideBlock.getMeasuredWidth();
                        right = slideBar.getMeasuredWidth();
                    }
                    LogUtils.showLog("left:"+left + "    right:"+right);
                    slideBlock.layout(left, top, right, bottom);
                    startX = currX;

                    if (popupWindow != null) {
                        popTextV.setText((currPage + 1) + "");
                        slideBlock.setText("" + (currPage+1));
                        // 设置popwindow的滑动
                        if ("no".equals(bound)) {
                            int[] loc = new int[2];
                            slideBar.getLocationInWindow(loc);
                            popupWindow.update(currX, loc[1] - dp40, popupWindow.getWidth(), popupWindow.getHeight(), true);
                        }
                    }
                }
                else if (MotionEvent.ACTION_UP == event.getAction()) {
                    popupWindow.dismiss();
                    if (onSlideChange != null) {
                        if (currPage == totalPage) {
                            // 防止ViewPager越界
                            currPage = totalPage - 1;
                        }
                        onSlideChange.onSlideChange(currPage);
                    }
                }
                return true;
            }
        });

        // 初始化PopupWindow
        View contentView = mInflater.inflate(R.layout.popup_view, null);
        popTextV = (TextView) contentView.findViewById(R.id.pop_text);
        popupWindow = new PopupWindow(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setContentView(contentView);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.pop_bg));
        popupWindow.setAnimationStyle(0);
    }

    public interface OnSlideChange {
        public void onSlideChange(int page);
    }

    OnSlideChange onSlideChange = null;
    public void setOnSlideChange(OnSlideChange onSlideChange) {
        this.onSlideChange = onSlideChange;
    }

    int totalPage = 0;
    // 设置总页数
    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    // 设置当前页数
    public void setCurrPage(int page) {
        currPage = page;
        int left = 0;
        if (page == 0) {
            left = 0;
        }
        else if (page == totalPage - 1) {
            left = slideBar.getMeasuredWidth() - slideBlock.getMeasuredWidth();
        }
        else {
            left = currPage * slideBar.getMeasuredWidth() / (totalPage - 1) - slideBlock.getMeasuredWidth() / 2;
        }
        int top = slideBlock.getTop();
        int right = left + slideBlock.getMeasuredWidth();
        int bottom = slideBlock.getBottom();
        slideBlock.layout(left, top, right, bottom);
    }
}
